package springmvc.dao;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DatabasePool {

    private static HikariDataSource hikariDataSource;

    public static HikariDataSource getHikariDataSource(){

        if(null != hikariDataSource){
            return hikariDataSource;
        }

        synchronized(DatabasePool.class){
            if(null == hikariDataSource){
                String jdbcurl = "jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC";
                String driverName = "com.mysql.cj.jdbc.Driver";
                HikariConfig hikariConfig = new HikariConfig();
                hikariConfig.setUsername("root");
                hikariConfig.setPassword("liuyuqi21");
                hikariConfig.setDriverClassName(driverName);
                hikariConfig.setJdbcUrl(jdbcurl);
                hikariDataSource = new HikariDataSource(hikariConfig);
                return hikariDataSource;
            }
        }
        return null;
    }

    public static void main(String[] args) {

        String sql = "SELECT password FROM student where sid= 1" ;
        try(Connection connection = DatabasePool.getHikariDataSource().getConnection()){
            try(Statement statement = connection.createStatement()){
                try(ResultSet resultSet = statement.executeQuery(sql)){
                    while (resultSet.next()){
                        System.out.println(resultSet.getString("password"));
                    }
                }
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
